package demo1;
import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student> {
    int age;
    String name;
    int score;

    public Student(String name, int age, int score) {
        this.age = age;
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override//这种写法有缺陷 这样比较形式就变得单一了
    public int compareTo(Student o) {
        if (this.age > o.age) {
            return 1;
        } else if (this.age < o.age) {
            return -1;
        } else return 0;

    }

    public static void sort(Comparable[] array) {
        for (int i = 0; i < array.length - 1; i++)
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j].compareTo(array[j + 1]) > 0) {
                    Comparable tmp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = tmp;
                }
            }
    }
}
class NameComparator implements Comparator<Student>{//名字比较器
    @Override
    public int compare(Student o1, Student o2) {//重写compara方法
        if(o1.name.compareTo(o2.name)>0) {
            return 1;
        } else if (o1.name.compareTo(o2.name)<0) {
            return -1;
        }else {
            return 0;
        }
    }
}
class AgeComparator implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        if(o1.age>o2.age)
            return 1;
        else if (o1.age<o2.age) {
            return -1;
        }else{
            return 0;
        }
    }
}

public class Test{
    public static void main(String[] args) {
        Student[] student = new Student[4];
        student[0] = new Student("lisi",18,88);
        student[1] = new Student("avb",15,99);
        student[2] = new Student("shabihan",112,99);
        student[3] = new Student("zhshan",10,99);
        //System.out.println(student[0].compareTo(student[1]));
        System.out.println(Arrays.toString(student));
        NameComparator nameComparator = new NameComparator();
        AgeComparator ageComparator = new AgeComparator();
        //Arrays.sort(student);
        Arrays.sort(student,ageComparator);//当含有名字比较器时，传参还需要传递比较器
        //Arrays.sort(student);//当没有比较器时，就这样传参
        System.out.println(Arrays.toString(student));
    }
}
